//
//  AppDelegate.m
//  project
//
//  Created by 黄建华 on 2017/9/23.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "SNNavigationViewController.h"
#import "CustomTabBar.h"
#import "LoginViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "BlueToothViewController.h"
#import "FileModelEntity.h"
#import <Bugly/Bugly.h>
#import "FileModelEntity.h"
#import "OTAUpdateFirmwareNordicVc.h"
@interface AppDelegate ()<UNUserNotificationCenterDelegate, UIAlertViewDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [NSThread sleepForTimeInterval:2.0];
    // Override point for customization after application launch.
    self.window                 = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [Bugly startWithAppId:@"dfd290d4a7"];
    //检查设备模型
    [[ShareData sharedInstance]checkDeviceModel];
    [[FileModelEntity sharedInstance]checkUpdateFirmwareInfo];

    [self createVideoFloders];
    //注册通知
    if (IOS10_OR_LATER) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound+UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError *_Nullable error) {
        }];
    } else {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings
                                                settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound
                                                categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
    // 状态栏设置为白色文字
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    if ([HASLOGIN getBOOLValue]) {
        [SN_Net getUserInfoWithSuccess:^(id object) {
            UserInfoModel *model = object;
            [KK_LastUser setObjectValue:model.user_id];
        } fail:^(id object) {
            
        }];
        [kK_App enterMainVc];
    } else {
        [self enterLoginVc];
    }
    [[ThirdLogin sharedInstance] registerActivePlatforms];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}

- (void)enterLoginVc {
    LoginViewController        *loginVc  = [[LoginViewController alloc]init];
    SNNavigationViewController *customVC = [[SNNavigationViewController alloc] initWithRootViewController:loginVc];
    
    self.window.rootViewController = customVC;
}

- (void)enterMainVc {
    if ([[UIApplication sharedApplication] currentUserNotificationSettings].types == UIUserNotificationTypeNone) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:HHH_Text(@"Please allow WellGo to active the pushing function") message:HHH_Text(@"WellGo is asking your permission to active incoming call、SMS、App pushing function") delegate:self cancelButtonTitle:HHH_Text(@"Deny") otherButtonTitles:HHH_Text(@"Allow"), nil];
        alertView.delegate = self;
        [alertView show];
    }
    [HASLOGIN setBOOLValue:YES];
    CustomTabBar               *guide    = [[CustomTabBar alloc]init];
    SNNavigationViewController *customVC = [[SNNavigationViewController alloc] initWithRootViewController:guide];
    
    [self loadTextFontColor];
    self.window.rootViewController = customVC;
}

- (void)pushUpdateVc {
    if ([HASLOGIN getBOOLValue]) {
        OTAUpdateFirmwareNordicVc           *vc       = [[OTAUpdateFirmwareNordicVc alloc] init];
        [vc delayShow];
        SNNavigationViewController *customVC = [[SNNavigationViewController alloc] initWithRootViewController:vc];
        self.window.rootViewController = customVC;
    }
}

- (void)loadTextFontColor {
    NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
    NSString       *str   = [userD objectForKey:@"themeColor"];
    NSInteger      i      = 0;
    
    if (!str) {
        i = 0xbe9f61;
    } else {
        if ([str isEqualToString:@"默认"]) {
            i = 0xbe9f61;
        } else if ([str isEqualToString:@"暗红"]) {
            i = 0xc50b30;
        } else if ([str isEqualToString:@"浅蓝"]) {
            i = 0x84b4e4;
        } else if ([str isEqualToString:@"深蓝"]) {
            i = 0x0195d3;
        } else if ([str isEqualToString:@"蓝黑"]) {
            i = 0xbe9f61;
        } else if ([str isEqualToString:@"鲜黄"]) {
            i = 0xfecf29;
        } else if ([str isEqualToString:@"橙黄"]) {
            i = 0xf66d1f;
        } else if ([str isEqualToString:@"紫色"]) {
            i = 0x3e2581;
        } else if ([str isEqualToString:@"粉红"]) {
            i = 0xff0066;
        } else if ([str isEqualToString:@"蓝色"]) {
            i = 0x0000fe;
        }
    }
    [userD setInteger:i forKey:@"themeHex"];
    [userD synchronize];
}

- (void)createVideoFloders {    // 通知不用上传备份
    [XYSandbox createDirectoryAtPath:[[XYSandbox docPath] stringByAppendingPathComponent:@"/db/"]];
    [XYSandbox createDirectoryAtPath:[[XYSandbox docPath] stringByAppendingPathComponent:@"/dbimg/"]];
    [[[XYSandbox docPath] stringByAppendingPathComponent:@"/db/"] addSkipBackupAttributeToItem];
    [[[XYSandbox docPath] stringByAppendingPathComponent:@"/dbimg/"] addSkipBackupAttributeToItem];
}

//ios10
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    if ([notification.request.identifier isEqualToString:@"findPhone"]) {
        return;
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
}

//ios8
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
     [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdateData) object:nil];
    [SN_Player pause];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
        [SN_Player play];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdateData) object:nil];
        [self performSelector:@selector(delayUpdateData) withObject:nil afterDelay:15.0];
}

- (void)delayUpdateData
{
    if (!KK_BLESend.isSend && KK_BLEModel.isConnected && SN_USER.autoUpdateData)
    {
        NSLog(@"进入前台刷新大数据>>>>>");
        
        [KK_BLESend updateData];
    }

}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

